package com.icesoft.base.admin.register;

import com.icesoft.base.admin.entity.Company;
import com.icesoft.base.admin.entity.SysUser;
import com.icesoft.base.admin.service.CompanyService;
import com.icesoft.base.admin.service.SysUserService;
import com.icesoft.base.manager.entity.security.SysRole;
import com.icesoft.base.manager.entity.system.SysOrg;
import com.icesoft.base.manager.service.security.SysRoleService;
import com.icesoft.base.manager.service.system.SysOrgService;
import lombok.AllArgsConstructor;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.core.annotation.Order;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

@Component
@Order(10)
@Profile({"default", "dev"})
@AllArgsConstructor
public class SysUserRegisterListener implements ApplicationRunner {
    private SysRoleService sysRoleService;
    private CompanyService companyService;
    private SysOrgService sysOrgService;
    private SysUserService sysUserService;
    private PasswordEncoder passwordEncoder;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        if (sysUserService.countAll() > 0) {
            return;
        }
        Company company = new Company();
        company.setName("系统公司");
        companyService.create(company);

        SysRole sysRole = new SysRole();
        sysRole.setName("默认角色");
        sysRoleService.create(sysRole);

        SysOrg sysOrg = new SysOrg();
        sysOrg.setName("系统组织");
        sysOrg.setCompanyId(company.getId());
        sysOrg.setPid(0);
        sysOrgService.create(sysOrg);

        SysUser user = new SysUser();
        user.setName("系统管理员");
        user.setUsername("admin");
        user.setPassword(passwordEncoder.encode("user@181"));
        user.setCompanyId(company.getId());
        user.setOrgId(sysOrg.getId());
        user.setPhone("18129375757");
        sysUserService.create(user);
    }
}
